import {
  addAchievTrans,
  delAchievTrans,
  getAchievTransList,
  upAchievTrans
} from "@/api/research/achievTrans";
import { getPatentList } from "@/api/research/patent";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import { type Ref, computed, h, onMounted, reactive, ref } from "vue";
import editForm from "../form/index.vue";
import showDetail from "../form/showDetail.vue";

import {
  dealDataExcept,
  dealDataRide,
  exportData,
  formatDate,
  getTableCol
} from "@/utils/common";
import {
  checkStatusRend,
  dataStatusRend,
  rejectDescRend,
  tableFileRend
} from "@/utils/table";
import dayjs from "dayjs";
import { useRoute } from "vue-router";

export function useUser(tableRef: Ref) {
  const form = reactive({
    patentName: "",
    patentType: "",
    examineStatus: "",
    status: "",
    firstInventorType: "",
    firstInventor: "",
    searchDate: [],
    acquisitionDateStart: "",
    acquisitionDateEnd: "",
    orderBy: "desc",
    pageNum: 1,
    pageSize: 10
  });
  const finalSearchForm = ref({});
  const formRef = ref();
  const dataList = ref([]);
  const allPatentList = ref([]);
  const loading = ref(true);
  const tableCol = ref<any>({});
  const treeData = ref([]);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "专利名称",
      prop: "patentName",
      fixed: "left",
      minWidth: 200
    },
    {
      label: "审核状态",
      prop: "examineStatus",
      minWidth: 90,
      cellRenderer: checkStatusRend
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: dataStatusRend
    },
    {
      label: "驳回原因",
      prop: "examineDesc",
      minWidth: 120,
      cellRenderer: rejectDescRend
    },
    {
      label: "专利类型",
      prop: "patentType",
      minWidth: 120
    },
    {
      label: "专利权人",
      prop: "patentee",
      minWidth: 100
    },
    {
      label: "第一发明人类型",
      prop: "firstInventorType",
      minWidth: 125
    },
    {
      label: "第一发明人",
      prop: "firstInventor",
      minWidth: 110
    },
    {
      label: "受让企业",
      prop: "acquisitionCompany",
      minWidth: 120
    },
    {
      label: "转让金额(万元)",
      prop: "acquisitionPrice",
      minWidth: 120,
      formatter: ({ acquisitionPrice }) => dealDataExcept(acquisitionPrice) || 0
    },
    {
      label: "转让合同签订日期",
      prop: "acquisitionDate",
      minWidth: 138,
      formatter: ({ acquisitionDate }) => formatDate(acquisitionDate)
    },
    {
      label: "转让合同",
      prop: "acquisitionFiles",
      minWidth: 110,
      cellRenderer: ({ row }) => tableFileRend(row, "acquisitionFiles")
    },
    {
      label: "获得积分",
      prop: "score",
      minWidth: 100
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "修改时间",
      prop: "gmtModified",
      minWidth: 140,
      formatter: ({ gmtModified }) =>
        dayjs(gmtModified).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "操作",
      prop: "operation",
      fixed: "right",
      align: "left",
      width: 190,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  const handleDelete = async row => {
    await delAchievTrans(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    let tempForm = { ...form };
    if (tempForm.searchDate && tempForm.searchDate.length > 0) {
      tempForm.acquisitionDateStart = tempForm.searchDate[0] + " 00:00:00";
      tempForm.acquisitionDateEnd = tempForm.searchDate[1] + " 23:59:59";
    }
    delete tempForm.searchDate;
    finalSearchForm.value = tempForm;
    const { data } = await getAchievTransList(tempForm);
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  // 导出数据
  const exportModuleData = () => {
    exportData(
      "成果转化",
      "/achievement/transformation/export",
      finalSearchForm.value
    );
  };

  function openDetail(title = "新增", row?) {
    addDialog({
      title: "查看成果转化",
      props: {
        formInline: {
          id: row?.id ?? undefined,
          createUserId: row?.createUserId ?? undefined,
          title,
          acquisitionCompany: row?.acquisitionCompany ?? "",
          acquisitionFiles: row?.acquisitionFiles ?? "",
          acquisitionDate: row?.acquisitionDate ?? "",
          acquisitionPrice: row?.acquisitionPrice ?? "",
          firstInventor: row?.firstInventor ?? "",
          firstInventorType: row?.firstInventorType ?? "",
          outId: row?.outId ?? undefined,
          patentName: row?.patentName ?? "",
          patentType: row?.patentType ?? "",
          patentee: row?.patentee ?? "",
          secondInventor: row?.secondInventor ?? "",
          secondInventorType: row?.secondInventorType ?? "",
          score: row?.score ?? null,
          examineStatus: row?.examineStatus ?? 0,
          examineDesc: row?.examineDesc ?? ""
        },
        allPatentList: allPatentList.value
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(showDetail),
      beforeSure: done => {
        done();
      }
    });
  }

  function openDialog(title = "新增", row?) {
    let patenteeList = [
      {
        patentee: ""
      }
    ];
    if (row?.patentee) {
      patenteeList = row.patentee.split(",").map(v => {
        return { patentee: v };
      });
    }
    addDialog({
      title: `${title}成果转化`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          title,
          acquisitionCompany: row?.acquisitionCompany ?? "",
          acquisitionFiles: row?.acquisitionFiles ?? "",
          acquisitionDate: formatDate(row?.acquisitionDate, ""),
          acquisitionPrice: dealDataExcept(row?.acquisitionPrice) ?? "",
          firstInventor: row?.firstInventor ?? "",
          firstInventorType: row?.firstInventorType ?? "",
          outId: row?.outId ?? undefined,
          patentName: row?.patentName ?? "",
          patentType: row?.patentType ?? "",
          patentee: row?.patentee ?? "",
          secondInventor: row?.secondInventor ?? "",
          secondInventorType: row?.secondInventorType ?? "",
          score: row?.score ?? null,
          patenteeList: patenteeList
        },
        allPatentList: allPatentList.value
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message("操作成功", { type: "success" });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            let formVal = { ...curData };
            formVal.score = formVal.score || 0;
            formVal.acquisitionPrice = dealDataRide(formVal.acquisitionPrice);
            if (formVal.patenteeList && formVal.patenteeList.length > 0) {
              formVal.patentee = formVal.patenteeList
                .filter(v => v.patentee)
                .map(v => v.patentee)
                .join(",");
            }
            delete formVal.patenteeList;
            console.log("formVal ", formVal);
            // 表单规则校验通过
            if (title === "新增") {
              await addAchievTrans(formVal);
              chores();
            } else {
              await upAchievTrans(formVal);
              chores();
            }
          }
        });
      }
    });
  }

  const loadPatentList = async () => {
    let params = {
      orderBy: "desc",
      // examineStatus: 1,
      pageNum: 1,
      pageSize: 500
    };
    let { data } = await getPatentList(params);
    allPatentList.value = data.records || [];
  };

  onMounted(async () => {
    const { query } = useRoute();
    if (query.examineStatus) {
      form.examineStatus = Number(query.examineStatus) as any;
    }
    if (query.status) {
      form.status = Number(query.status) as any;
    }
    tableCol.value = await getTableCol("achievTrans");

    onSearch();

    loadPatentList();
  });

  return {
    form,
    tableCol,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    openDetail,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    exportModuleData
  };
}
